package controller;

import com.google.gson.Gson;
import dao.WorkOrderDao;
import dao.impl.WorkOrderDaoImpl;
import entry.WorkOrder;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;

@WebServlet("/work/*")
public class WorkServlet extends HttpServlet {
    WorkOrder workOrder = new WorkOrder();
    WorkOrderDao workOrderDao = new WorkOrderDaoImpl();

    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        request.setCharacterEncoding("utf-8");
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json;charset=utf-8");
        String url = request.getRequestURI();
        String methodName = url.substring(url.lastIndexOf("/") + 1);
        Class cla = WorkServlet.class;
        try {
            Method method = cla.getMethod(methodName, HttpServletRequest.class, HttpServletResponse.class);
            method.invoke(cla.newInstance(), request, response);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }

    public void addWork(HttpServletRequest request, HttpServletResponse response) throws IOException {

        int id = Integer.parseInt(request.getParameter("id"));
        String executor = request.getParameter("executor");
        String description = request.getParameter("description");
        int orderLevel = Integer.parseInt(request.getParameter("orderLevel"));

        workOrder.setpId(id);
        workOrder.setExecutor(executor);
        workOrder.setDescription(description);
        workOrder.setOrderLevel(orderLevel);


        int i = workOrderDao.insertWork(workOrder);
        boolean b = i == 0 ? false : true;
        Gson gson = new Gson();
        String s = gson.toJson(b);
        response.getWriter().println(s);
    }

    public void sel(HttpServletRequest request, HttpServletResponse response) throws IOException {
        ArrayList list = workOrderDao.selectAll();
        Gson gson=new Gson();
        response.getWriter().println(gson.toJson(list));
    }
}
